package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.domain.vo.SoundVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.SoundApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Service
public class PeachblossomService {
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Reference
    private SoundApi soundApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    final private String GET_SOUND_REMAINING_TIMES_KEY = "GET_SOUND_REMAINING_TIMES_";
    
    /**
     * 桃花传音-发送语音
     *
     * @param soundFile
     * @return
     */
    public ResponseEntity<Object> save(MultipartFile soundFile) throws IOException {
        //获取用户ID
        Long userId = UserHolder.getUserId();
        //文件上传到fastdfs
        String fileName = soundFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
        String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        
        //文件路径保存到mongodb
        Sound sound = new Sound(ObjectId.get(), userId, soundUrl);
        soundApi.save(sound);
        return ResponseEntity.ok(null);
    }
    
    /**
     * 查找语音
     *
     * @return
     */
    public ResponseEntity<Object> getSound() {
        //获取用户ID
        Sound sound = null;
        Long userId = UserHolder.getUserId();
        //查找出一条数据，然后删除。多线程操作共享数据，上锁
        synchronized (PeachblossomService.class) {
            sound = soundApi.findOne();
            //soundApi.deleteById(sound.getId());
        }
        
        SoundVo soundVo = null;
        UserInfo userInfo = userInfoApi.findById(userId);
        //封装前端所需要的数据
        if (sound != null && userInfo != null) {
            soundVo = new SoundVo();
            
            soundVo.setId(userId);
            soundVo.setAvatar(userInfo.getAvatar());
            soundVo.setNickname(userInfo.getNickname());
            soundVo.setGender(userInfo.getGender());
            soundVo.setAge(userInfo.getAge());
            soundVo.setSoundUrl(sound.getSoundUrl());
            String s = redisTemplate.opsForValue().get(GET_SOUND_REMAINING_TIMES_KEY + userId);
            
            LocalDate today = LocalDate.now();
            Date tomorrow = Date.from(today.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
            if (!StringUtils.isEmpty(s)) {
                Integer remainingTimes = Integer.parseInt(s);
                //设置可接受音频的剩余次数
                soundVo.setRemainingTimes(remainingTimes);
                remainingTimes--;
                redisTemplate.opsForValue().set(GET_SOUND_REMAINING_TIMES_KEY + userId, remainingTimes.toString());
                //设置数据在第二天凌晨0点过期
                redisTemplate.expireAt(GET_SOUND_REMAINING_TIMES_KEY + userId, tomorrow);
            } else {
                redisTemplate.opsForValue().set(GET_SOUND_REMAINING_TIMES_KEY + userId, String.valueOf(9));
                //设置数据在第二天凌晨0点过期
                soundVo.setRemainingTimes(9);
            }
            
        }
        
        return ResponseEntity.ok(soundVo);
    }
    
    
}
